<template>
  <!-- 成本价管理 -->
  <div>
    <custom-container ref="customContainerRef" :config="mainConfig"></custom-container>
    <setForm
      ref="setFormRef"
      @changeList="handleQuery"
    ></setForm>
    <!-- 价格管理 -->
    <PriceDetailDialog
      ref="priceMangementRef"
    >
    </PriceDetailDialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineAsyncComponent } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import usedicts, { DictDirection } from '@/store/modules/dicts'
import { getcostPriceList, deleteecostPrice } from '@/api/BusinessConfig/costPriceManagement'

const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const PriceDetailDialog = defineAsyncComponent(() => import('./components/PriceDetailDialog.vue'))
const dicts = usedicts()
const { t } = useI18n()
const params = { pageSize: 10, pageNum: 1 }
const queryParams = ref(params)
const multiple = ref(false)
const single = ref(false)
const priceMangementRef = ref(null)
const deleteLoading = ref<boolean>(false)
let ids = []
const
  customContainerRef = ref(null),
  setFormRef = ref(null)
const handleQuery = () => {
  customContainerRef.value.getList()
}
const handleTableSelect = (rows:{[key:string]:any}[]) => {
  ids = rows.map(el => el.id)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
const handelAdd = () => {
  setFormRef.value.open('新增')
}
const handleUpdate = (row:{[key:string]:any}[]) => {
  setFormRef.value.open('修改', row)
}
// 删除成本价
const handleDelete = (row:{[key:string]:any}[]) => {
  deleteLoading.value = true
  const rowList = JSON.parse(JSON.stringify(row))
  const id = rowList.id || ids
  ElMessageBox.confirm(`是否确认删除成本价编号为"${ id }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => deleteecostPrice(id))
  .then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('删除成功')
      deleteLoading.value = false
    } else {
      deleteLoading.value = false
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => { error === 'cancel' && ElMessage.info('取消删除') })
}
// 价格管理
const handlePriceDetail = (row) => {
  priceMangementRef.value.open(row.id)
}
const mainConfig = computed(() => {
  const queryFeild = 'BusinessConfiguration.costPriceManagement.queryField.'
  const btns = 'BusinessConfiguration.costPriceManagement.btns.'
  const columns = 'BusinessConfiguration.costPriceManagement.columns.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryFeild }serviceChannel`),
          prop: 'serviceChannelId',
          align: 'center',
        },
        {
          label: t(`${ queryFeild }nameOfCostPrice`),
          prop: 'printCode',
          align: 'center',
        },
      ],
      queryParams: queryParams.value,
      formOption: {
        labelWidth: '100px',
      },
    },
    btns: [
      {
        title: t(`${ btns }add`),
        type: 'primary',
        onClick: handelAdd,
      },
      {
        title: t(`${ btns }delete`),
        type: 'danger',
        disabled: multiple.value,
        onClick: handleDelete,
      },
    ],
    table: {
      columns: [
        { type: 'selection', width: '55', align: 'center' },
        {
          label: t(`${ columns }serviceChannel`),
          prop: 'serviceChannelId',
          align: 'center',
          width: '180',
          formatter: (row) => dicts.getDictLabel({ dict: DictDirection.服务渠道, value: row.serviceChannelId }),
        },
        {
          label: t(`${ columns }nameOfCostPrice`),
          prop: 'costPriceName',
          align: 'center',
          width: '180',
        },
        {
          label: t(`${ columns }typeOfGoods`),
          prop: 'goodsType',
          align: 'center',
          formatter: (row) => dicts.getDictLabel({ dict: DictDirection.包裹类型, value: row.goodsType }),
        },
        {
          label: t(`${ columns }paymentMethod`),
          prop: 'paymentMethod',
          align: 'center',
          formatter: (row) => dicts.getDictLabel({ dict: DictDirection.付款方式, value: row.paymentMethod }),
        },
        {
          label: t(`${ columns }operation`),
          align: 'center',
          width: '200',
          fixed: 'right',
          showOverflowTooltip: false,
          className: 'custormFixedCol',
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ btns }edit`),
                clickFun: handleUpdate,
              },
              {
                title: t(`${ btns }delete`),
                clickFun: handleDelete,
              },
              {
                title: t(`${ btns }priceManagement`),
                clickFun: handlePriceDetail,
              },
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleTableSelect(rows)
        },
      },
    },
    api: getcostPriceList,
    customKey: 'BusinessConfiguration/costPriceManagement',
  }
})
</script>